<template> 
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="150px">
          <el-form-item label="专题名称/标题：">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="标题"></el-input>
          </el-form-item>
          <el-form-item label="创建时间：">
            <el-date-picker
              class="input-width"
              v-model="createTime"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="启用状态：">
            <el-select v-model="listQuery.showStatus" class="input-width" placeholder="全部" clearable>
              <el-option v-for="item in showStatusOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推荐状态：">
            <el-select v-model="listQuery.recommendStatus" class="input-width" placeholder="全部" clearable>
              <el-option v-for="item in recommendStatusOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>专题列表</span>
      <el-button
        class="btn-add"
        @click="handleAddSubject()"
        size="mini">
        添加
      </el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="orderTable"
                :data="list"
                style="width: 100%;"
                @selection-change="handleSelectionChange"
                v-loading="listLoading" border>
        <el-table-column type="selection" width="89" align="center"/>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="专题标题" width="300" align="center">
          <template slot-scope="scope">{{scope.row.title}}</template>
        </el-table-column>
        <el-table-column label="专题描述" width="300" align="center">
          <template slot-scope="scope">{{scope.row.description}}</template>
        </el-table-column>
        <el-table-column label="专题分类" width="300" align="center">
          <template slot-scope="scope">{{scope.row.categoryName}}</template>
        </el-table-column>
        <el-table-column label="关联产品数量" width="300" align="center">
          <template slot-scope="scope">{{scope.row.productCount}}</template>
        </el-table-column>
        <el-table-column label="收藏数量" width="300" align="center">
          <template slot-scope="scope">{{scope.row.collectCount}}</template>
        </el-table-column>
        <el-table-column label="评论数量" width="300" align="center">
          <template slot-scope="scope">{{scope.row.commentCount}}</template>
        </el-table-column>
        <el-table-column label="创建时间" width="300" align="center">
          <template slot-scope="scope">{{scope.row.createTime | formatCreateTime}}</template>
        </el-table-column>
        <el-table-column label="是否显示" width="110" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleShowStatusChange(scope.$index, scope.row)"
              :active-value=1
              :inactive-value=0
              v-model="scope.row.showStatus">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否推荐" width="110" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleRecommendChange(scope.$index, scope.row)"
              :active-value=1
              :inactive-value=0
              v-model="scope.row.recommendStatus">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEditSubject(scope.$index, scope.row)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDeleteSubject(scope.$index, scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
      <el-select
        size="small"
        v-model="operateType" placeholder="批量操作">
        <el-option
          v-for="item in operateOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchOperate()"
        type="primary"
        size="small">
        确定
      </el-button>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit?'编辑专题':'添加专题'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="40%">
      <el-form :model="subject"
               ref="subjectForm"
               label-width="150px" size="small">
        <el-form-item label="专题标题：">
          <el-input v-model="subject.title" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="专题分类：">
          <el-select
            v-model="subject.categotyId"
            @change="handleSubjectCateChange"
            placeholder="请选择专题分类">
            <el-option
              v-for="item in subjectCateList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专题描述：">
          <el-input v-model="subject.description" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="排序：">
          <el-input v-model="subject.sort" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="是否启用：">
          <el-radio-group v-model="subject.showStatus">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
    import {getPage, deleteSubject, createSubject, updateSubject, updateShowStatus, updateRecommendStatus} from '@/api/subject';
    import {getListAll} from "@/api/subjectCate";
    import {formatDate} from '@/utils/date';

    const defaultListQuery = {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        showStatus: null,
        recommendStatus: null,
        startTime: null,
        endTime: null,
    };
    const defaultSubject = {
        id: null,
        title: null,
        description: null,
        categoryId: null,
        categoryName: null,
        productCount: 0,
        collectCount: 0,
        commentCount: 0,
        createTime: null,
        sort: 0,
        showStatus: 0,
        recommendStatus: 0
    };
    export default {
        name: "subjectList",
        data() {
            return {
                subject: Object.assign({}, defaultSubject),
                listQuery: Object.assign({}, defaultListQuery),
                subjectCateList: null,
                createTime: null,
                listLoading: true,
                list: null,
                total: null,
                isEdit: false,
                dialogVisible: false,
                operateType: null,
                cateOptions: [],
                multipleSelection: [],
                operateOptions: [
                    {
                        label: '批量删除',
                        value: 0
                    },
                    {
                        label: '取消显示',
                        value: 1
                    },
                    {
                        label: '全部显示',
                        value: 2
                    },
                    {
                        label: '取消推荐',
                        value: 3
                    },
                    {
                        label: '全部推荐',
                        value: 4
                    },
                ],
                showStatusOptions: [
                    {
                        label: '否',
                        value: 0
                    },
                    {
                        label: '是',
                        value: 1
                    }
                ],
                recommendStatusOptions: [
                    {
                        label: '否',
                        value: 0
                    },
                    {
                        label: '是',
                        value: 1
                    }
                ]
            }
        },
        created() {
            this.getList();
            this.getSubjectCate();
        },
        filters: {
            formatCreateTime(time) {
                let date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
            },
        },
        methods: {
            getSubjectCate() {
              getListAll().then((response) => {
                  subjectCateList = response.data;
              })
            },
            handleResetSearch() {
                this.listQuery = Object.assign({}, defaultListQuery);
                this.createTime = null;
                this.getList();
            },
            handleSearchList() {
                this.listQuery.pageNum = 1;
                this.getList();
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            handleEditSubject(index, row) {
                this.dialogVisible = true;
                this.isEdit = true;
                this.subject = Object.assign({}, row);
            },
            handleDeleteSubject(index, row) {
                let ids = [];
                ids.push(row.id);
                this.deleteSubject(ids);
            },
            handleBatchOperate() {
                if (this.operateType == null) {
                    this.$message({
                        message: '请选择操作类型',
                        type: 'warning',
                        duration: 1000
                    });
                    return;
                }
                if (this.multipleSelection == null || this.multipleSelection.length < 1) {
                    this.$message({
                        message: '请选择要操作的专题',
                        type: 'warning',
                        duration: 1000
                    });
                    return;
                }
                let ids = [];
                let value = -1;
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    ids.push(this.multipleSelection[i].id);
                }
                switch (this.operateType) {
                    case this.operateOptions[0].value:
                        this.deleteBatchSubject(ids);
                        break;
                    case this.operateOptions[1].value:
                        value = 0;
                    case this.operateOptions[2].value:
                        this.$confirm('是否要进行该批量操作?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            this.updateShowStatus(value == 0 ? 0 : 1, ids);
                        }).catch(() => {})
                        break;
                    case this.operateOptions[3].value:
                        value = 0;
                    case this.operateOptions[4].value:
                        this.$confirm('是否要进行该批量操作?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            this.updateRecommendStatus(value == 0 ? 0 : 1, ids);
                        }).catch(() => {})
                        break;
                    default:
                        break;
                }
            },
            handleSizeChange(val) {
                this.listQuery.pageNum = 1;
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getList();
            },
            handleShowStatusChange(index, row) {
                this.$confirm('是否要修改该状态?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let ids = [];
                    ids.push(row.id);
                    this.updateShowStatus(row.showStatus, ids);
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消修改'
                    });
                    this.getList();
                });
            },
            updateShowStatus(showStatus, ids) {
                let params = new URLSearchParams();
                params.append('ids', ids);
                params.append('showStatus', showStatus);
                updateShowStatus(params).then(async response => {
                    this.$message({
                        message: '修改成功',
                        type: 'success',
                        duration: 1000
                    });
                    await this.getList();
                });
            },
            handleRecommendStatusChange(index, row) {
                this.$confirm('是否要修改该状态?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let ids = [];
                    ids.push(row.id);
                    this.updateRecommendStatus(row.showStatus, ids);
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消修改'
                    });
                    this.getList();
                });
            },
            updateRecommendStatus(recommendStatus, ids) {
                let params = new URLSearchParams();
                params.append('ids', ids);
                params.append('recommendStatus', recommendStatus);
                updateShowStatus(params).then(async response => {
                    this.$message({
                        message: '修改成功',
                        type: 'success',
                        duration: 1000
                    });
                    await this.getList();
                });
            },
            getList() {
                this.listLoading = true;
                if (this.createTime != null){
                    this.listQuery.startTime = this.createTime[0]
                    this.listQuery.startTime = this.createTime[1]
                }
                getPage(this.listQuery).then(response => {
                    this.listLoading = false;
                    this.list = response.data.list;
                    this.total = response.data.total;
                });
            },
            deleteBatchSubject(ids) {
                this.$confirm('是否要进行该删除操作?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params = new URLSearchParams();
                    params.append("ids", ids);
                    deleteSubject(params).then(async response => {
                        this.$message({
                            message: '删除成功！',
                            type: 'success',
                            duration: 1000
                        });
                        await this.getList();
                    });
                }).catch(()=>{})
            },
            handleAddSubject() {
                this.dialogVisible = true;
                this.isEdit = false;
                this.subject = Object.assign({}, defaultSubject);
            },
            handleDialogConfirm() {
                this.$confirm('是否要确认?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (this.isEdit) {
                        updateSubject(this.subject.id, this.subject).then(response => {
                            this.$message({
                                message: '修改成功！',
                                type: 'success'
                            });
                            this.dialogVisible = false;
                            this.getList();
                        })
                    } else {
                        createSubject(this.subject).then(response => {
                            this.$message({
                                message: '添加成功！',
                                type: 'success'
                            });
                            this.dialogVisible = false;
                            this.getList();
                        })
                    }
                })
            },
        }
    }
</script>
<style scoped>
  .input-width {
    width: 260px;
  }

  /*解决日期选择器中间字显示不全问题（样式穿透）*/
  /deep/ .el-range-separator {
    width: 40px !important;
  }
</style>
